package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.feign.MemberFeignService;
import com.atguigu.common.to.ware.FreightRespTo;
import com.atguigu.common.to.ware.MemberAddressTo;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareInfoDao;
import com.atguigu.gulimall.ware.entity.WareInfoEntity;
import com.atguigu.gulimall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();

        /**
         * key:
         */
        String key = params.getOrDefault("key", "").toString();
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                // id	name	address	areacode
                w.eq("id", key)
                        .or().like("name", key)
                        .or().like("address", key)
                        .or().like("areacode", key);
            });
        }


        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FreightRespTo getFreight(Long addrId) {
        FreightRespTo vo = new FreightRespTo();
        R r = memberFeignService.addressInfo(addrId);
        if (r.isOk()) {
            MemberAddressTo data = r.getData("memberReceiveAddress", new TypeReference<MemberAddressTo>() {
            });
            String phone = data.getPhone();
            String str = phone.substring(phone.length() - 1);
            BigDecimal freight = new BigDecimal(str);
            vo.setAddress(data);
            vo.setFreight(freight);
            return vo;
        }
        return null;
    }

}